<?

//require_once(dirname(__FILE__) . '/../abstract/http.php');

class bf_http_sock extends bf_http {

	public function get($url, $params = array(), $auth = array()) {

		$p = (is_array($params) ? $this->build_params($params) : $params);

		$url = parse_url($url);
		if ($url['scheme'] != 'http')
			return false;

		$host = $url['host'];
		$path = $url['path'];
		$port = (isset($url['port']) ? $url['port'] : 80);
 
		$errno = $errstr = '';
		if ($fp = @fsockopen($host, $port, $errno, $errstr, $this->opts['timeout'])) {
 
			@fputs($fp, "GET $path?$p HTTP/1.1\r\n");
			@fputs($fp, "Host: $host\r\n");
			@fputs($fp, "Connection: close\r\n\r\n");
			@fputs($fp, $p);
	 
			$response = ''; 
			while(!feof($fp))
				$response .= @fgets($fp);
	
			@fclose($fp);

			return $this->parse_respone($response);
		}

		return false;
	}

	public function post($url, $params = array(), $auth = array()) {

		$p = (is_array($params) ? $this->build_params($params) : $params);

		$url = parse_url($url);
		if ($url['scheme'] != 'http')
			return false;

		$host = $url['host'];
		$path = $url['path'];
		$port = (isset($url['port']) ? $url['port'] : 80);
 
		$errno = $errstr = '';
		if ($fp = @fsockopen($host, $port, $errno, $errstr, $this->opts['timeout'])) {
 
			@fputs($fp, "POST $path HTTP/1.1\r\n");
			@fputs($fp, "Host: $host\r\n");
			@fputs($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
			@fputs($fp, "Content-Length: ". strlen($p) ."\r\n");
			@fputs($fp, "Connection: close\r\n\r\n");
			@fputs($fp, $p);
	 
			$response = ''; 
			while(!feof($fp))
				$response .= @fgets($fp);
	
			@fclose($fp);

			return $this->parse_respone($response);
		}

		return false;
	}

	protected function parse_respone($response) {

		$result = explode("\r\n\r\n", $response, 2);
	 
		$headers = (isset($result[0]) ? $result[0] : '');
		$content = (isset($result[1]) ? $result[1] : '');

		$m = array();
		if (!preg_match('/^HTTP\/1\.1\s+(\d+)/i', $headers, $m))
			return false;

		if (preg_match('/Transfer\-Encoding\:\s+chunked/i', $headers))
			$content = $this->chunked_decode($content);

		return array('status' => $m[1], 'response' => $content);
	}

	protected function chunked_decode($content) {
		$m = array();
		if (preg_match('/^([0-9a-f]+)\r\n/i', $content, $m)) {
			if (($chunk_size = hexdec($m[1])) == 0)
				return '';			
			$start = strlen($m[0]);
			$chunk = substr($content, $start, $chunk_size);
			return $chunk . $this->chunked_decode(substr($content, $start + $chunk_size + 2));
		}
	}
}

?>